﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net.Http; // HttpClient 调用后端
using Newtonsoft.Json; // 反序列化
using Mes.Production.Common; // ApiResponse包装
using Mes.Production.Config; // Api地址
using Mes.Production.Models; // 详情模型
using Mes; // 使用 HttpClientHelper

namespace Mes.Production
{
    public partial class ProductionDetailFrm : Form
    {
        private readonly int _orderId; // 订单Id
        // 切换为使用 HttpClientHelper
        private readonly string _apiBaseUrl = ApiConfig.GetApiBaseUrl(); // API基础地址

        /// <summary>
        /// 构造函数：接收订单Id
        /// </summary>
        public ProductionDetailFrm(int orderId)
        {
            InitializeComponent();
            _orderId = orderId;
            this.Load += async (s, e) => await LoadDetailAsync(); // 加载即获取数据
        }

        /// <summary>
        /// 从后端获取详情并绑定到界面
        /// </summary>
        private async Task LoadDetailAsync()
        {
            try
            {
                var url = $"{_apiBaseUrl}/api/ProductionOrder/GetProductionOrderDetail?id={_orderId}";
                var json = await HttpClientHelper.ClientAsync("GET", url, false, null);
                var result = JsonConvert.DeserializeObject<ApiResponse<ProductionOrderDetailDto>>(json);
                if (result == null || result.Data == null)
                {
                    MessageBox.Show("未获取到订单详情", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }

                // 绑定头部信息
                this.textOrderNumber.Text = result.Data.OrderNumber;
                this.textOrderSource.Text = GetOrderSourceText(result.Data.OrderSource);
                this.textRemarks.Text = result.Data.Remarks;
                this.textCreateTime.Text = result.Data.CreateTime?.ToString("yyyy-MM-dd HH:mm") ?? string.Empty;

                // 绑定明细列表
                this.gridItems.DataSource = result.Data.Items;
                ConfigureItemGridHeaders();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载详情失败：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 明细表头中文与格式
        /// </summary>
        private void ConfigureItemGridHeaders()
        {
            var grid = this.gridItems;
            if (grid.Columns.Contains("Id")) grid.Columns["Id"].Visible = false;
            if (grid.Columns.Contains("MaterialId")) grid.Columns["MaterialId"].Visible = false;
            if (grid.Columns.Contains("FinishedNo")) grid.Columns["FinishedNo"].HeaderText = "成品编号";
            if (grid.Columns.Contains("FinishedName")) grid.Columns["FinishedName"].HeaderText = "成品名称";
            if (grid.Columns.Contains("Specification")) grid.Columns["Specification"].HeaderText = "规格";
            if (grid.Columns.Contains("Unit")) grid.Columns["Unit"].HeaderText = "单位";
            if (grid.Columns.Contains("PlannedQuantity")) grid.Columns["PlannedQuantity"].HeaderText = "计划数量";
            if (grid.Columns.Contains("DeliveryDate"))
            {
                grid.Columns["DeliveryDate"].HeaderText = "交付日期";
                grid.Columns["DeliveryDate"].DefaultCellStyle.Format = "yyyy-MM-dd";
            }
        }

        /// <summary>
        /// 订单来源中文映射
        /// </summary>
        private string GetOrderSourceText(int sourceId)
        {
            switch (sourceId)
            {
                case 1: return "手工录入";
                case 2: return "系统下发";
                case 3: return "APS调度";
                default: return "未知";
            }
        }
    }
}
